$(function (){
	var container = $(".container"), nums = [];
	function restart(){
		container.find(".bg, .num").remove();
		for(var i = 0; i < 16; i++){
			container.append('<div class="bg"></div>');	
		}
		for(var i = 0; i < 4; i++){
			nums[i] = [0,0,0,0]
		}
		container.append(randomNum());
		container.append(randomNum());
	}
	function random(x){
		return Math.floor(Math.random() * x) 	
	}
	function randomNum(){
		while(container.find(".num").length < 16){
			var x = random(4), y = random(4);
			if(nums[x][y] == 0){
				var num = Math.random() * 10 < 9 ? 2 : 4;
				var numDiv = $('<div class="num">'+num+'</div>');
				xy(numDiv, x, y, num);	
				return numDiv;		
			}
		}
	}
	function xy(numDiv, x, y, num){
		nums[x][y] = num;
		numDiv.attr("class", "num num"+x+y +" numc"+num).css({left: 125 * x + 12 + "px", top: 125 * y + 12 + "px"}).html(num).fadeIn(500);
	}
	$(document).keydown(function (event){
		switch(event.keyCode){
			case 37 : move(-1, 0); return false;
			case 38 : move(0, -1); return false;
			case 39 : move(1, 0); return false;
			case 40 : move(0, 1); return false;	
		}
	});
	
	function move(xd, yd){
		var xs = xd > 0 ? 3 : 0, ys = yd > 0 ? 3 : 0, xt = xs > 0 ? -1 : 1, yt = ys > 0 ? -1 : 1;
		for(var x = xs; 0 <= x && x <= 3; x += xt){
			for(var y = ys; 0 <= y && y <= 3; y+= yt){
				moveNumDiv(x, y, xd, yd);	
			}
		}
		container.append(randomNum());
	}
	function moveNumDiv(x, y, xd, yd){
		if(nums[x][y] == 0) return;
		var numDiv = $(".num" + x + y), num = nums[x][y], tx = x, ty = y, sameNum = false;
		if(xd != 0){
			for(var i = x + xd; 0 <= i && i <= 3; i += xd){
				if(nums[i][y] == 0){
					tx = i;
				}else if (nums[i][y] == num){
					tx = i;
					sameNum = true;
				}else{
					break;	
				}
			}
		}else{
			for(var i = y + yd; 0 <= i && i <= 3; i += yd){
				if(nums[x][i] == 0){	
					ty = i;
				}else if (nums[x][i] == num){
					ty = i;
					sameNum = true;
				}else{
					break;	
				}
			}
		}
		if(sameNum){
			nums[x][y] = 0;
			$(".num" + tx + ty).remove();
			xy(numDiv, tx, ty, num * 2);
		}else if( x != tx || y != ty){
			nums[x][y] = 0;
			xy(numDiv, tx, ty, num);
		}
	}
	restart();
});